import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener{
	Image img;
	int hx,hy;
	int width, height;
	Color penColor = Color.black; //white is erase
	int penSize = 3;
	protected int gridSize = 18; //Adjust wipes board as well

	DrawingPanel (int wi, int he) {
		addMouseListener(this);
		addMouseMotionListener(this);
		width = wi;
		height = he;
		this.setPreferredSize(new Dimension(wi, he));
	}

    public void mousePressed(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {
		hx=0; hy=0;
	}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mouseClicked(MouseEvent e) {}
	public void mouseDragged(MouseEvent e) {
		Graphics g = img.getGraphics();
		int x = e.getX();
		int y = e.getY();
		int lessX; int greatX;
		if (x<hx){
			lessX = x; greatX = hx;
		}else{
			lessX = hx; greatX = x;
		}
		if(lessX!=0){
			setThickLine(g,penSize);
			g.setColor(penColor);
			g.drawLine(x,y,hx,hy);
			paintGrid(g,gridSize);
		}
		hx = x;
		hy = y;
	}

	public void paintComponent(Graphics g){
		super.paintComponent(g);
		if(img == null) {
            img = createImage(width, height);
            g = img.getGraphics();
            g.setColor(Color.white);
            g.fillRect(0,0,width,height);
			paintGrid(g, gridSize);
            g.dispose();
        }
		g.drawImage(img, 0, 0, this);
		repaint();
	}
	public void paintGrid(Graphics g, int gridSize){
		g.setColor( Color.black );
		setThickLine(g,1);
		for(int x=10; x<width; x+=gridSize){
			g.drawLine(x,0,x,900);
		}
		for(int y=10; y<height; y+=gridSize){
			g.drawLine(0,y,900,y);
		}
		repaint();
	}
	public void setThickLine(Graphics g, int width){
		Graphics2D g2d = (Graphics2D)g;
	    g2d.setStroke(new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
	}

}